﻿using STHPMS1.Common.C_Entity;
using STHPMS1.Common.C_Entity.Stmpms1;
using STHPMS1.ICore;
using STHPMS1.ICore.I_Core;
using STHPMS1.ICore.I_UI;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data;
using System.IO;
using System.Reflection;
using STHPMS1.ICore.I_Serv;
using System.Collections.Generic;
using STHPMS1.ICore.I_Entity.Stmpms1;

namespace STHPMS1.Web.W_Controller
{
    [RoutePrefix("api/axleload")]
    public class S_AxleloadPage1Controller : STHPMS1.Web.W_Core.MyController
    {
        [Route("")]
        [Route("page/{page?}", Name = "GetaxleloadByPage")]
        [Route("rows/{rows?}")]
        [Route("page/{page?}/rows/{rows?}")]
        public IHttpActionResult Get(string address = null, DateTime? checkDate = null, int page = 1, int rows = 10)
        {
            int p = page;
            int s = rows;

            PagingInfo info = new PagingInfo();
            info.PageIndex = p > 0 ? p - 1 : 0;
            info.PageSize = s;
            info.TotalRecords = 0;

            Expression<Func<S_Axleload, bool>> exp = null;
            if (((address != null && address.ToString().Length > 0)) && (checkDate != null))
            {
                exp = pre => (pre.Statname.Contains(address.ToString())) && (pre.Obvtm == checkDate);
            }
            else if (address != null && address.ToString().Length > 0)
            {
                exp = pre => pre.Statname.Contains(address.ToString());
            }
            else if (checkDate != null)
            {
                exp = pre => pre.Obvtm == checkDate;
            }


            var data = this.Scene.Bll.S_Axleload.Get<S_Axleload>(exp, info).ToArray();
            if (data == null) return NotFound();

            var result = new { rows = data, total = info.TotalRecords };

            return Ok(result);
        }

        [Route("")]
        public HttpResponseMessage Post(S_AxleModel entity)
        {
            HttpResponseMessage response = null;
            List<IS_Apply> applyList = new List<IS_Apply>();
            if (string.IsNullOrEmpty(entity.Applyid))
            {
                if (string.IsNullOrEmpty(entity.ApplyStake))
                {
                    response = Request.CreateResponse(HttpStatusCode.InternalServerError);
                    return response;
                }

                foreach (var item in entity.ApplyStake.Split(';'))
                {
                    if (string.IsNullOrEmpty(item)) continue;
                    string[] arr = item.Split(',');


                    S_Apply apply = new S_Apply();
                    apply.Appbeginmp = float.Parse(arr[1]);
                    apply.Appendmp = float.Parse(arr[2]);
                    apply.Apprdid = arr[0];
                    apply.Direction_Dictid = int.Parse(arr[3]);
                    apply.Applyid = this.Scene.Bll.S_Apply.SaveApply(apply);
                    applyList.Add(apply);

                    entity.Axleid = MyApp.Locator.GetInstance<IKeyGenrateService>().NewGuid();
                    if (entity.His_Version == 0)
                        entity.His_Version = this.Scene.Bll.B_Roadway.GetNewHistoryVersion(apply.Apprdid, false);

                    entity.Applyid = apply.Applyid;
                    entity.Importdate = DateTime.Now;
                    this.Scene.Bll.S_Axleload.Save((S_Axleload)entity);

                }
            }
            else
            {
                if (string.IsNullOrEmpty(entity.Ealf_Dictid)) throw new Exception("轴型不能内容为空!");
                var length = entity.Ealf_Dictid.Split('+').Length;
                if (length < 3)
                {
                    entity.Eaweight3 = null;
                    entity.Eaweight4 = null;
                }
                else if (length < 4)
                {
                    entity.Eaweight4 = null;
                }
                entity.Importdate = DateTime.Now;
                this.Scene.Bll.S_Axleload.Save((S_Axleload)entity);

                S_Apply apply = this.Scene.Dal.Sthpms1.SingleById<S_Apply>(entity.Applyid);
                applyList.Add(apply);
            }

            if (applyList.Count > 0)
                this.Scene.Bll.Dm_Trafaxle.CalacAxleLoadAndAge(applyList);

            response = Request.CreateResponse(HttpStatusCode.Created);
            // Generate a link to the new book and set the Location header in the response.
            string uri = Url.Link("GetaxleloadByPage", new { page = 1 });
            response.Headers.Location = new Uri(uri);

            return response;
        }

        [Route("")]
        public void Delete(S_Axleload entity)
        {
            this.Scene.Bll.S_Axleload.Remove(entity);
        }

        #region 导入处理


        /// <summary>
        /// 反射获取对象的所有属性
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        private PropertyInfo[] GetAllProperty(object t)
        {
            Type temp = t.GetType();
            return temp.GetProperties();
        }
        /// <summary>
        /// 获取交通量的实体
        /// </summary>
        /// <param name="excel">导入的Excel</param>
        /// <param name="Rdwayid">路线编号</param>
        /// <param name="bmp">起始桩号</param>
        /// <param name="emp">结束桩号</param>
        ///<param name="startRow">提取位置</param>
        /// <param name="dir">方向</param>
        /// <returns></returns>
        private DataTable GetData(DataTable excel, int startRow, List<IS_Apply> applyList)
        {
            List<string> keys = new List<string>();
            DataTable kh = new DataTable();
            PropertyInfo[] propertys = GetAllProperty(new S_Axleload());
            foreach (PropertyInfo p in propertys)
            {
                kh.Columns.Add(new DataColumn(p.Name.ToUpper()));
            }
            kh.Columns.Add(new DataColumn("index")); //记录错误行号
            if (excel.Rows.Count == 0)
            {
                throw new Exception("Excel没有数据");
            }
            int index = startRow + 1;
            foreach (DataRow r in excel.Rows)
            {
                string _svydata = r[0].ToString();//观测时间
                string _STATNAME = r[1].ToString();//观测地点
                string _REPREVEH_DICTID_temp = r[2].ToString().Trim();//代表车型
                int _REPREVEH_DICTID = GetCar(_REPREVEH_DICTID_temp);
                if (_REPREVEH_DICTID == -1)
                {
                    throw new Exception("第" + (index + 1) + "行没有此类车型名称");
                }
                string _EALF_DICTID_temp = r[3].ToString().Trim();//轴型
                int _EALF_DICTID = GetEalf(_REPREVEH_DICTID, _EALF_DICTID_temp);
                if (_EALF_DICTID == -1)
                {
                    throw new Exception("第" + (index + 1) + "行没有此类车型没有匹配的轴型名称");
                }
                string _EAWEIGHT1 = r[4].ToString();//前轴
                string _EAWEIGHT2 = r[5].ToString();//中前轴
                string _EAWEIGHT3 = r[6].ToString();//中后轴
                string _EAWEIGHT4 = r[7].ToString();//后轴 
                string rdid = r[9].ToString();//路线编号
                double start = Convert.ToDouble(r[10]);//起点
                double end = Convert.ToDouble(r[11]);//终点
                //验证路线和起终点桩号
                B_Roadway roads = GetRoad(rdid);
                //检查起点和终点桩号是否符合该路线的交通量划分标准
                this.Scene.Bll.B_Rdstandard.CheckMp(rdid, start, end);
                string dir_temp = r[12].ToString();//方向
                if (dir_temp == "全幅")
                {
                    //保存或修改应用区间表
                    S_Apply apply = new S_Apply();
                    apply.Appbeginmp = start;
                    apply.Appendmp = end;
                    apply.Apprdid = rdid;
                    apply.Direction_Dictid = (int)Common.C_Enum.DirectionEnum.All13;
                    apply.Applyid = this.Scene.Bll.S_Apply.SaveApplyBack(apply); //保存并返回应用区间ID
                    applyList.Add(apply);

                    DataRow dr = kh.NewRow();
                    dr["AXLEID"] = Guid.NewGuid().ToString();//轴载ID
                    dr["APPLYID"] = apply.Applyid;  //应用区间ID
                    dr["OBVTM"] = _svydata; //观测时间
                    dr["STATNAME"] = _STATNAME;//观测地点
                    dr["REPREVEH_DICTID"] = _REPREVEH_DICTID;//车辆类型 ;
                    dr["EALF_DICTID"] = _EALF_DICTID;//轴型
                    dr["EAWEIGHT1"] = _EAWEIGHT1 == "" ? null : _EAWEIGHT1;
                    dr["EAWEIGHT2"] = _EAWEIGHT2 == "" ? null : _EAWEIGHT2;
                    dr["EAWEIGHT3"] = _EAWEIGHT3 == "" ? null : _EAWEIGHT3;
                    dr["EAWEIGHT4"] = _EAWEIGHT4 == "" ? null : _EAWEIGHT4;
                    dr["HIS_VERSION"] = this.Scene.Bll.B_Roadway.GetNewHistoryVersion(rdid);//版本号
                    dr["IMPORTDATE"] = DateTime.Now.ToShortDateString(); 
                    dr["index"] = index++;
                }
                else
                {
                    //上行
                    S_Apply apply = new S_Apply();
                    apply.Appbeginmp = start;
                    apply.Appendmp = end;
                    apply.Apprdid = rdid;
                    apply.Direction_Dictid = (int)Common.C_Enum.DirectionEnum.Up11;
                    apply.Applyid = this.Scene.Bll.S_Apply.SaveApplyBack(apply); //保存并返回应用区间ID
                    applyList.Add(apply);
                    DataRow dr = kh.NewRow();
                    dr["AXLEID"] = Guid.NewGuid().ToString();//轴载ID
                    dr["APPLYID"] = apply.Applyid;  //应用区间ID
                    dr["OBVTM"] = _svydata; //观测时间
                    dr["STATNAME"] = _STATNAME;//观测地点
                    dr["REPREVEH_DICTID"] = _REPREVEH_DICTID;//车辆类型 ;
                    dr["EALF_DICTID"] = _EALF_DICTID;//轴型
                    dr["EAWEIGHT1"] = _EAWEIGHT1 == "" ? null : _EAWEIGHT1;
                    dr["EAWEIGHT2"] = _EAWEIGHT2 == "" ? null : _EAWEIGHT2;
                    dr["EAWEIGHT3"] = _EAWEIGHT3 == "" ? null : _EAWEIGHT3;
                    dr["EAWEIGHT4"] = _EAWEIGHT4 == "" ? null : _EAWEIGHT4;
                    dr["HIS_VERSION"] = this.Scene.Bll.B_Roadway.GetNewHistoryVersion(rdid);//版本号
                    dr["IMPORTDATE"] = DateTime.Now.ToShortDateString();
                    dr["index"] = index++;
                    kh.Rows.Add(dr);

                    //下行
                    apply = new S_Apply();
                    apply.Appbeginmp = start;
                    apply.Appendmp = end;
                    apply.Apprdid = rdid;
                    apply.Direction_Dictid = (int)Common.C_Enum.DirectionEnum.Down12;
                    apply.Applyid = this.Scene.Bll.S_Apply.SaveApplyBack(apply); //保存并返回应用区间ID
                    applyList.Add(apply);
                    dr = kh.NewRow();
                    dr["AXLEID"] = Guid.NewGuid().ToString();//轴载ID
                    dr["APPLYID"] = apply.Applyid;  //应用区间ID
                    dr["OBVTM"] = _svydata; //观测时间
                    dr["STATNAME"] = _STATNAME;//观测地点
                    dr["REPREVEH_DICTID"] = _REPREVEH_DICTID;//车辆类型 ;
                    dr["EALF_DICTID"] = _EALF_DICTID;//轴型
                    dr["EAWEIGHT1"] = _EAWEIGHT1 == "" ? null : _EAWEIGHT1;
                    dr["EAWEIGHT2"] = _EAWEIGHT2 == "" ? null : _EAWEIGHT2;
                    dr["EAWEIGHT3"] = _EAWEIGHT3 == "" ? null : _EAWEIGHT3;
                    dr["EAWEIGHT4"] = _EAWEIGHT4 == "" ? null : _EAWEIGHT4;
                    dr["HIS_VERSION"] = this.Scene.Bll.B_Roadway.GetNewHistoryVersion(rdid);//版本号
                    dr["IMPORTDATE"] = DateTime.Now.ToShortDateString();
                    dr["index"] = index++;
                    kh.Rows.Add(dr);
                }
            }
            return kh;
        }
        /// <summary>
        /// 路线信息
        /// </summary>
        /// <param name="stru_id"></param>
        /// <returns></returns>
        public B_Roadway GetRoad(string rdid)
        {
            List<B_Roadway> lst = null;
            if (!Common.C_Utils.MyCacheTools.IsCacheExist(rdid))
            {
                lst = this.Scene.Bll.B_Roadway.SearchById<B_Roadway>(rdid);
                Common.C_Utils.MyCacheTools.SetCache(rdid, lst, 24);
            }
            else
            {
                lst = Common.C_Utils.MyCacheTools.GetCache(rdid) as List<B_Roadway>;
            }
            if (lst.Count > 0)
                return lst[0];
            return null;
        }

        /// <summary>
        /// 返回车型值
        /// </summary>
        /// <param name="car"></param>
        /// <returns></returns>
        private int GetCar(string car)
        {
            if (car=="小型载重汽车")
            {
                return (int)Common.C_Enum.CarEnum.C1000;
            }
            else if (car == "中型载重汽车")
            {
                return (int)Common.C_Enum.CarEnum.C1001;
            }
            else if (car == "大型载重汽车")
            {
                return (int)Common.C_Enum.CarEnum.C1002;
            }
            else if (car == "特大型载重汽车")
            {
                return (int)Common.C_Enum.CarEnum.C1003;
            }
            else if (car=="小型客车")
            {
                return (int)Common.C_Enum.CarEnum.C1004;
            }
            else if (car == "大型客车")
            {
                return (int)Common.C_Enum.CarEnum.C1005;
            }
            else if (car=="拖挂车")
            {
                return (int)Common.C_Enum.CarEnum.C1006;
            }
            else if (car=="集装箱车")
            {
                return (int)Common.C_Enum.CarEnum.C1007;
            }
            else if (car=="拖拉机")
            {
                return (int)Common.C_Enum.CarEnum.C1008;
            }
            return -1;
        }

        /// <summary>
        /// 返回轴型
        /// </summary>
        /// <param name="car"></param>
        /// <param name="ealf"></param>
        /// <returns></returns>
        private int GetEalf(int car, string ealf)
        {
            if (car == 1000 || car == 1001) //载重小型或中型
            {
                if (ealf == "1s+1s") return 1100;
            }
            else if (car == 1002) //载重大型
            {
                if (ealf == "1s+1d") return 1101;
            }
            else if (car == 1003) //载重特大型
            {
                if (ealf == "1s+1s+2d") return 1103;
                else if (ealf == "1s+1d+2d") return 1105;
                else if (ealf == "1s+1d+3d") return 1106;
                else if (ealf == "1s+2d+3d") return 1107;
            }
            else if (car == 1004) // 小型客车
            {
                if (ealf == "1s+1s") return 1100;
                else if (ealf == "1s+1d") return 1101;
            }
            else if (car == 1005) //大型客车
            {
                if (ealf == "1s+1d") return 1101;
                else if (ealf == "1s+2d") return 1102;
            }
            else if (car == 1006) //拖挂车
            {
                if (ealf == "1s+1d") return 1101;
                else if (ealf == "1s+1s+1d") return 1104;
                else if (ealf == "1s+2d") return 1102;
                else if (ealf == "1s+1s+2d") return 1103;
                else if (ealf == "1s+2d+3d") return 1107;
            }
            else if (car == 1007) //集装箱车
            {
                if (ealf == "1s+1s+1d") return 1104;
                else if (ealf == "1s+2d") return 1102;
                else if (ealf == "1s+2s+2d") return 1103;
                else if (ealf == "1s+1s+2d") return 1103;
                else if (ealf == "1s+1d+3d") return 1106;
                else if (ealf == "1s+2d+3d") return 1107;
            }
            else if (car == 1008) //拖拉机
            {
                if (ealf == "1s+1s") return 1100;
            }
            return -1;
        }

        [Route("uploadFile")]
        public void PostUploadFile()
        {

            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            string uploadPath =
              System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Upload") + "\\";
            string PhysicalPath = "";
            if (hfc.Count > 0)
            {
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                PhysicalPath = uploadPath + hfc[0].FileName;
                hfc[0].SaveAs(PhysicalPath);
            }

            System.Web.HttpContext.Current.Response.Write(PhysicalPath);
            System.Web.HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 上传数据处理
        /// </summary>
        /// <param name="file">文件路径</param>
        /// <param name="rdid">路线编号</param>
        /// <param name="bmp">起始桩号</param>
        /// <param name="emp">结束桩号</param>
        /// <param name="dir">方向</param>
        /// <returns></returns>
        [Route("saveFile")]
        public HttpResponseMessage PostSaveFile(string file)
        {
            DataTable entity = null;//实体数据
            Excel_BaseImportData exData = null;//导入数据
            if (File.Exists(file))
            {
                try
                {
                    int startRow = 1;//Excel列头位置

                    DataTable dt = Common.C_Excel.ExcelTool.RenderDataTableFromExcel(file, startRow);//获取Excel的DataTable
                    //验证Excel表头格式?

                    List<IS_Apply> applyList = new List<IS_Apply>();
                    //插入应用区间表
                    //foreach (var item in ApplyStake.Split(';'))
                    //{
                    //    if (string.IsNullOrEmpty(item)) continue;
                    //    string[] arr = item.Split(',');


                    //    S_Apply apply = new S_Apply();
                    //    apply.Appbeginmp = float.Parse(arr[1]);
                    //    apply.Appendmp = float.Parse(arr[2]);
                    //    apply.Apprdid = arr[0];
                    //    apply.Direction_Dictid = int.Parse(arr[3]);
                    //    apply.Applyid = this.Scene.Bll.S_Apply.SaveApply(apply); //保存并返回应用区间ID

                    //applyList.Add(apply);
                    //}
                    //一个应用区间ID对应交通量的数据
                    entity = GetData(dt, startRow, applyList);//将要导入的实体Table
                    exData = new Excel_BaseImportData(new S_Axleload());//轴载实体
                    exData.DtSource = entity;
                    exData.TableName = "S_AXLELOAD"; //轴载
                    this.Scene.Bll.Excel.ImportData(exData); //导入数据





                    if (applyList.Count > 0)
                        this.Scene.Bll.Dm_Trafaxle.CalacAxleLoadAndAge(applyList);

                }
                catch (Exception ex)
                {
                    File.Delete(file);//删除上传数据
                    //抛出错误
                    var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content = new StringContent(ex.Message),
                        ReasonPhrase = "Server Error"
                    };
                    throw new HttpResponseException(response);
                }
            }
            else
            {
                //抛出错误
                var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent("服务器未能保存上传文件，请联系管理员"),
                    ReasonPhrase = "Server Error"
                };
                throw new HttpResponseException(response);
            }
            var res = Request.CreateResponse(HttpStatusCode.Created);
            string uri = Url.Link("GetaxleloadByPage", new { page = 1 });
            res.Headers.Location = new Uri(uri);

            return res;
        }
        #endregion

    }

    public class S_AxleModel : S_Axleload
    {
        public string ApplyStake { get; set; }
    }

}

